package com.beemans.topon.views

import android.widget.FrameLayout
import com.beemans.topon.kts.onVisibilityChange

/**
 * @author ti
 * @date 2022/11/23.
 */
class ExposureHelper {

    /**
     * 视图是否处于屏幕可见
     */
    var isLocalVisible: Boolean = false
        private set

    fun init(frameLayout: FrameLayout, onVisible: (isVisible: Boolean) -> Unit) {
        frameLayout.apply {
            /**
             * 视图处于屏幕可见判断至少需要有一个像素点
             */
            val lp = layoutParams ?: FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.WRAP_CONTENT,
                FrameLayout.LayoutParams.WRAP_CONTENT
            )
            layoutParams = lp.apply {
                if (minimumHeight == 0) {
                    minimumHeight = 1
                }
                if (minimumWidth == 0) {
                    minimumWidth = 1
                }
            }

            /**
             * 视图是否可见监听
             */
            onVisibilityChange { _, isVisible ->
                this@ExposureHelper.isLocalVisible = isVisible
                onVisible.invoke(isVisible)
            }
        }
    }
}